﻿using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using DBEntitie;
using System.Data;
using lhservice.Models;
using System.Reflection;

namespace lhservice.common
{
  public class MpServiceHelper
  {
    public class ResOfSendMsgToCustomer
    {
      public int errcode { get; set; }
      public string errmsg { get; set; }
    }
    public static string GetErrText(int errnum)
    {
      switch (errnum)
      {
        case 0:
          return "请求成功";
        case -1:
          return "系统繁忙，此时请开发者稍候再试";
        case 40001:
          return "获取 access_token 时 AppSecret 错误，或者 access_token 无效。请开发者认真比对 AppSecret 的正确性，或查看是否正在为恰当的小程序调用接口";
        case 40002:
          return "不合法的凭证类型";
        case 40003:
          return "不合法的 OpenID，请开发者确认 OpenID 是否是其他小程序的 OpenID";
        case 45015:
          return "回复时间超过限制";
        case 45047:
          return "客服接口下行条数超过上限";
        case 48001:
          return "API 功能未授权，请确认小程序已获得该接口";
        default:
          return "未知错误编码";
      }
    }

    public static string GetNoteOfService(string uid)
    {

      using (var db = new SyBaseEntities())
      {
        var sql = $"select cnote from namekf where ccode = '{uid}'";
        var data = db.FirstOrDefault(sql);
        return data[0].ToString();
      }

    }


    public static long GetMaxOrderNum(string sessionid)
    {
      using (var db = new SyBaseEntities())
      {
        var sql = $"select max(OrderNum) from z_service_msg where SessionId = '{sessionid}'";
        var data = db.FirstOrDefault(sql);
        var dd = data[0].ToString();
        var maxsn = string.IsNullOrEmpty(dd) ? 1 : int.Parse(dd) + 1;
        return maxsn;
      }
    }

    public static bool SaveMsg(MsgOfSave msg)
    {
      bool isFirst = true;
      string fields = "";
      string values = "";
      msg.OrderNum = GetMaxOrderNum(msg.SessionId);
      msg.State = 0;
      foreach (PropertyInfo p in msg.GetType().GetProperties())
      {
        if (p.GetValue(msg) == null) continue;

        if (!isFirst)
        {
          fields += ",";
          values += ",";
        }
        fields += $"{p.Name}";
        values += p.PropertyType == typeof(string) ? $"'{p.GetValue(msg)}'" : $"{p.GetValue(msg)}";
        if (isFirst) isFirst = false;
      }
      string isread = msg.Dir == "c2s" ? "0" : "1";

      var sql = $"insert into z_service_msg ( {fields},isread ) values ( {values},{isread})";

      using (var db = new SyBaseEntities())
      {
        db.Execute(sql);
      }
      return true;
    }

    /// <summary>
    /// 通过 sessionid 获取 客户的openid
    /// </summary>
    /// <param name="sessionid"></param>
    /// <returns></returns>
    public static string GetOpenidBySession(string sessionid)
    {
      string openid = "";
      using (var db = new SyBaseEntities())
      {
        var sql = $"select openid from z_session where session_id ='{sessionid}' ";
        var data = db.FirstOrDefault(sql);
        openid = data == null ? "" : data[0].ToString();
      }
      return openid;
    }

    public static string GetAskidBySession(string sessionid)
    {
      string askid = "";
      using (var db = new SyBaseEntities())
      {
        var sql = $"select aid from z_ask where session_id ='{sessionid}' ";
        var data = db.FirstOrDefault(sql);
        askid = data == null ? "" : data[0].ToString();
      }
      return askid;
    }

    /// <summary>
    /// 回复消息给客户
    /// /// </summary>
    /// <param name="ReMsg"></param>
    public static int SendMsgToCustomer(MsgToCustomer ReMsg)
    {
      string ttoken = MpToken.GetToken();
      var url = $"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={ttoken}";
      var client = new HttpClient();
      var con = JsonConvert.SerializeObject(ReMsg);
      StringContent content = new StringContent(con, Encoding.UTF8, "application/json");
      string res = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
      var returns = JsonConvert.DeserializeObject<ResOfSendMsgToCustomer>(res);
      return returns.errcode;
    }

    /// <summary>
    /// 通过 sessionid 获取 客户的编号
    /// </summary>
    /// <param name="sessionid"></param>
    /// <returns></returns>
    public static string GetCustomerId(string sessionid)
    {
      var sql = $@"select customer_id as '客户编号' from  z_session where session_id = '{sessionid}'";
      var cid = "";
      using (var db = new SyBaseEntities())
      {
        var data = db.FirstOrDefault(sql);
        cid = data != null ? data[0].ToString() : "";
      };
      return cid;
    }

    /// <summary>
    /// 通过客服ID 获取客服信息
    /// </summary>
    /// <param name="uid"></param>
    /// <returns></returns>
    public static Dictionary<string, dynamic> GetUserInfo(string uid)
    {
      var sql = $@"select * from z_servicer where  uid = '{uid}'";
      var res = new Dictionary<string, dynamic>();
      using (var db = new SyBaseEntities())
      {
        var table = db.QueryTable(sql);
        if (table == null) return res;

        foreach (DataRow row in table.Rows)
        {
          foreach (DataColumn col in table.Columns)
          {
            var name = col.ColumnName.ToString();
            res[PublicHelper.Ibm850ToGbk(name)] = row[name];
          }
        }
      };
      return res;
    }

    public static List<Dictionary<string, dynamic>> GetMsgList(string sid)
    {
      var sql = $@"update z_service_msg set isread = 1  where  SessionId = '{sid}'";
      var res = new List<Dictionary<string, dynamic>>();
      using (var db = new SyBaseEntities())
      {
        db.Execute(sql);
        sql = $@"select *,'' as 'callBackId' from z_service_msg  where  SessionId = '{sid}'";
        var table = db.QueryTable(sql);
        res = table.ToList();
      };
      return res;
    }


    public class ResOfJoinSession
    {
      public string ErrCode { get; set; }
      public string Err { get; set; }
      public string session_id { get; set; }
      public string servicerid { get; set; }
      public SessionDetail Detail { get; set; }
    }

    public class SessionDetail
    {
      public string customer { get; set; }
      public string customer_id { get; set; }
      public string lastMsgSendTime { get; set; }
      public string lastMsg { get; set; }
      public string openid { get; set; }
      public string isread { get; set; }
      public string sender { get; set; }
    }

    /// <summary>
    /// 客服接入会话登记
    /// </summary>
    /// <param name="sessionid"></param>
    /// <param name="servicerid"></param>
    /// <returns></returns>
    public static ResOfJoinSession JoinSession(string sessionid, string servicerid)
    {
      var res = new ResOfJoinSession();
      res.session_id = sessionid;
      using (var db = new SyBaseEntities())
      {
        var sql = $@"select session_state,servicer_id,customer_id,customer,create_dt,openid from z_session where session_id = '{sessionid}'";
        var rowdata = db.FirstOrDefault(sql);
        if (rowdata == null)
        {
          res.ErrCode = "1";
          res.Err = "无效会话！无法接入";
          return res;
        }

        string state = rowdata[0].ToString();

        if (state == "0")
        {
          res.ErrCode = "2";
          res.Err = "会话已关闭！无法接入";
          return res;
        }

        if (state == "100" && rowdata[1].ToString() != servicerid)
        {
          res.ErrCode = "3";
          res.Err = "会话已有其他客服接入";
          return res;
        }

        if (state != "100")
        {
          sql = $@"update z_session set servicer_id = '{servicerid}',session_state = 100 where session_id = '{sessionid}'";
          db.Execute(sql);

          var ReMsg = new MsgToCustomer()
          {
            touser = MpServiceHelper.GetOpenidBySession(sessionid),
            msgtype = "text",
            text = new MsgToCustomerText() { content = MpServiceHelper.GetNoteOfService(servicerid) }
          };
          MpServiceHelper.SendMsgToCustomer(ReMsg);
        }

        res.Err = "正常接入";
        res.ErrCode = "0";
        res.servicerid = servicerid;

        var _Detail = new SessionDetail();
        _Detail.customer = rowdata[3].ToString();
        _Detail.customer_id = rowdata[2].ToString();
        _Detail.openid = rowdata[5].ToString();


        sql = $@"select b.Sender from z_session a, z_ask b  
                where a.session_id*=b.session_id and a.session_id = '{sessionid}'";
        _Detail.sender = db.QueryTable(sql).ToList()[0]["Sender"];

        sql = $@"select 
                  CreateTime,Content,MsgType,isread 
                  from z_service_msg 
                  where 
                  SessionId = '{sessionid}' and 
                  OrderNum in (select max(OrderNum) from z_service_msg where SessionId = '{sessionid}')";
        rowdata = db.FirstOrDefault(sql);
        _Detail.lastMsgSendTime = rowdata[0].ToString();
        _Detail.lastMsg = rowdata[2].ToString() == "image" ? "收到图片" : rowdata[1].ToString();
        _Detail.isread = rowdata[3].ToString();
        res.Detail = _Detail;
        return res;
      }
    }

    /// <summary>
    /// 关闭会话
    /// </summary>
    /// <param name="sid"></param>
    public static void CloseSession(string sid)
    {
      using (var db = new SyBaseEntities())
      {
        var sql = $@"update z_session set session_state = 0 where session_id = '{sid}'";
        db.Execute(sql);
      }
    }

    /// <summary>
    /// 获取 sessionid列表 
    /// </summary>
    /// <param name="servicerid"></param>
    /// <param name="state"></param>
    /// <param name="keyword"></param>
    /// <returns></returns>
    public static Dictionary<string, dynamic> GetSessionList(string servicerid, int state, string keyword = "")
    {
      var sessionList = new Dictionary<string, dynamic>();
      using (var db = new SyBaseEntities())
      {
        var sql = $@"select 
          a.session_id,a.customer_id,a.customer,a.create_dt,b.Ask,b.Sender,b.Phone 
            from z_session a, z_ask b  where a.session_id*=b.session_id and session_state = {state} ";
        if (servicerid != "") sql += $" and servicer_id = '{servicerid}' ";
        if (keyword != "") sql += $" and (customer_id like '%{keyword}%' or customer like '%{keyword}%' )";
        var table = db.QueryTable(sql);
        if (table == null) return sessionList;
        foreach (DataRow row in table.Rows)
        {
          var detail = new Dictionary<string, string>()
          {
            ["session_id"] = row[0].ToString(),
            ["customer_id"] = row[1].ToString(),
            ["customer"] = row[2].ToString(),
            ["create_dt"] = row[3].ToString(),
            ["Ask"] = row[4].ToString(),
            ["Sender"] = row[5].ToString(),
            ["Phone"] = row[6].ToString()
          };
          sessionList[row[0].ToString()] = detail;
        }
      }
      return sessionList;
    }

    /// <summary>
    /// 获取未接通会话sessionid列表 
    /// </summary>
    /// <returns></returns>
    public static Dictionary<string, dynamic> GetNoJoinSessionList()
    {
      return GetSessionList("", 1);
    }


    /// <summary>
    /// 用户账号密码验证
    /// </summary>
    /// <param name="uid"></param>
    /// <param name="pwd"></param>
    /// <returns></returns>
    public static List<Dictionary<string, dynamic>> Vaild(string uid, string pwd)
    {
      List<Dictionary<string, dynamic>> res;
      using (var db = new SyBaseEntities())
      {
        string sql = $"select * from namekf where ccode='{uid}' and cpassowrd= '{pwd}'";
        res = db.QueryTable(sql).ToList();
      }
      return res;
    }

    /// <summary>
    /// 获取进行中会话sessionid列表 
    /// </summary>
    /// <returns></returns>
    public static Dictionary<string, dynamic> GetActiveSessionList(string servicerid)
    {
      return GetSessionList(servicerid, 100);
    }

    public static bool ModifyCustomer(string sid, string customer)
    {

      using (var db = new SyBaseEntities())
      {
        string sql = $"update z_session set customer='{customer}' where session_id='{sid}'";
        db.Execute(sql);
        return true;
      }
    }
    /// <summary>
    /// 校验openid有没有未绑定的ask记录
    /// 返回 true 是有
    /// </summary>
    /// <param name="openid"></param>
    /// <returns></returns>
    public static bool CheckAskBindWithOpenid(string openid)
    {
      bool res = false;
      using (var db = new SyBaseEntities())
      {
        var sql = $"select count(0) from z_ask where openid='{openid}' and IsBind='N'";
        var rowitem = db.FirstOrDefault(sql);
        if (rowitem[0].ToString() != "0") res = true;
      }
      return res;
    }
  }
}
